package com.grade.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.grade.common.constant.Constants;
import com.grade.common.core.domain.Ztree;
import com.grade.common.core.domain.entity.SysDept;
import com.grade.common.core.domain.entity.SysDictData;
import com.grade.common.core.domain.entity.SysUser;
import com.grade.common.utils.DateUtils;
import com.grade.common.utils.ShiroUtils;
import com.grade.common.utils.StringUtils;
import com.grade.common.utils.spring.SpringUtils;
import com.grade.system.domain.*;
import com.grade.system.mapper.*;
import com.grade.system.service.ISysDictDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.grade.system.service.ICreditGradeService;
import com.grade.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 信用评分Service业务层处理
 *
 * @author grade
 * @date 2021-10-17
 */
@Service
public class CreditGradeServiceImpl implements ICreditGradeService {
    @Autowired
    private CreditGradeMapper creditGradeMapper;
    @Autowired
    private GradeTemplateMapper gradeTemplateMapper;
    @Autowired
    private GradeItemMapper gradeItemMapper;
    @Autowired
    private GradeTypeMapper gradeTypeMapper;
    @Autowired
    private ItemTemplateRelationMapper itemTemplateRelationMapper;
    @Autowired
    private ItemGradeRelationMapper itemGradeRelationMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private CreditGradeTypeMapper creditGradeTypeMapper;

    /**
     * 查询信用评分
     *
     * @param id 信用评分主键
     * @return 信用评分
     */
    @Override
    public CreditGrade selectCreditGradeById(Long id) {
        return creditGradeMapper.selectCreditGradeById(id);
    }

    /**
     * 查询信用评分列表
     *
     * @param creditGrade 信用评分
     * @return 信用评分
     */
    @Override
    public List<CreditGrade> selectCreditGradeList(CreditGrade creditGrade) {
        return creditGradeMapper.selectCreditGradeList(creditGrade);
    }

    /**
     * 新增信用评分
     *
     * @param creditGrade 信用评分
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCreditGrade(CreditGrade creditGrade) {
        creditGrade.setCreateTime(DateUtils.getNowDate());
        Double totalScore = 0.00;
        Double maxScore = 0.0;
        Double weight=0.00;

        List<String> scores = creditGrade.getScores();
        List<String> remarks = creditGrade.getRemarks();

        //查询顶层目录评分类型
        List<GradeType> topGradeTypeList=gradeTypeMapper.selectTopGradeTypeByTemplateId(creditGrade.getTemplateId());

        //获取同样排序的评分细则数据
        GradeItem condition = new GradeItem();
        condition.setTemplateId(creditGrade.getTemplateId());
        List<GradeItem> relationList = gradeItemMapper.selectGradeItemList(condition);

        //评分数据集
        List<ItemGradeRelation> itemGradeRelationList = new ArrayList<>();
        for (int i = 0; i < scores.size() && i<remarks.size(); i++) {
            GradeItem gradeItem =new GradeItem();
            if(i<relationList.size()){
                gradeItem = relationList.get(i);
            }
            ItemGradeRelation itemGradeRelation = new ItemGradeRelation();
            BeanUtils.copyProperties(gradeItem, itemGradeRelation);
            itemGradeRelation.setScore(Double.parseDouble(scores.get(i)));
            itemGradeRelation.setItemId(gradeItem.getId());
            itemGradeRelation.setRemark(remarks.get(i));
            itemGradeRelation.setOrderNum(gradeItem.getItemOrder());
            itemGradeRelation.setDiagnoseRemark("");

            itemGradeRelationList.add(itemGradeRelation);
        }

        //按照不同的顶层目录计算分数
        String typeIds="";
        Double totalScore_Deduct = 0.00; //顶层可抵扣分数
        Double totalScore_NoDeduct=0.00; //顶层不可抵扣分数
        for(int j=0;j<topGradeTypeList.size();j++){
            //获取该顶层目录下的分类数据
            totalScore_Deduct=0.00;
            totalScore_NoDeduct=0.00;
            typeIds=gradeTypeMapper.selectGradeTypeChilds(topGradeTypeList.get(j).getTypeId());
            String[] arr_TypeIds=Convert.toStrArray(typeIds);
            for(int k=0;k<itemGradeRelationList.size();k++){
                ItemGradeRelation itemGradeRelation=itemGradeRelationList.get(k);
                if (itemGradeRelation!=null && Arrays.asList(arr_TypeIds).contains(itemGradeRelation.getTypeId().toString())){
                    // 计算可抵扣分数
                    if (itemGradeRelation.getDeductFlag().equals("0") && itemGradeRelation.getWeight()==null) {
                        totalScore_Deduct += itemGradeRelation.getScore();
                    }else if (itemGradeRelation.getDeductFlag().equals("0") && itemGradeRelation.getWeight()!=null){
                        totalScore_Deduct += itemGradeRelation.getWeight()*itemGradeRelation.getScore()/100;
                    }

                    //计算不可抵扣分数
                    if (itemGradeRelation.getDeductFlag().equals("1") && itemGradeRelation.getWeight()==null) {
                        totalScore_NoDeduct += itemGradeRelation.getScore();
                    }else if (itemGradeRelation.getDeductFlag().equals("1") && itemGradeRelation.getWeight()!=null){
                        totalScore_NoDeduct += itemGradeRelation.getWeight()*itemGradeRelation.getScore()/100;
                    }
                }
            }
            //判断该顶层目录是否存在封顶分数
            if (topGradeTypeList.get(j).getMaxScore()!=null && topGradeTypeList.get(j).getMaxScore()<totalScore_Deduct){
                totalScore_Deduct=Double.parseDouble(topGradeTypeList.get(j).getMaxScore().toString());
            }

            totalScore+=totalScore_Deduct+totalScore_NoDeduct;
        }

        //更新maxScore 、totalscore
        //creditGrade.setMaxScore(maxScore);
        GradeTemplate gradeTemplate=new GradeTemplate();
        gradeTemplate=gradeTemplateMapper.selectGradeTemplateById(creditGrade.getTemplateId());
        if (gradeTemplate!=null){
            creditGrade.setMaxScore(Double.parseDouble(gradeTemplate.getTotalScore().toString()));
        }
        creditGrade.setTotalScore(totalScore);
        //更新layer
        if(gradeTemplate!=null){
            creditGrade.setLayer(gradeTemplate.getLayer());
        }
        creditGradeMapper.insertCreditGrade(creditGrade);
        for (ItemGradeRelation igr : itemGradeRelationList) {
            igr.setGradeId(creditGrade.getId());
        }

        itemGradeRelationMapper.batchItemGrade(itemGradeRelationList);

        //新增预评分分类
        List<GradeType> gradeTypeList = gradeTypeMapper.selectGradeTypeByTemplateId(creditGrade.getTemplateId());
        for(int k=0;k<gradeTypeList.size();k++){
            CreditGradeType creditGradeType =new CreditGradeType();
            BeanUtils.copyProperties(gradeTypeList.get(k), creditGradeType);
            creditGradeType.setGradeId(creditGrade.getId());
            creditGradeTypeMapper.insertCreditGradeType(creditGradeType);
        }

        return 1;
    }

    public List<Ztree> treeData(CreditGrade creditGrade) {
        List<SysDictData> dictDataList = sysDictDataMapper.selectDictDataByType("b_city");
        List<CreditGrade> gradList = creditGradeMapper.selectCreditGradeList(creditGrade);
        List<Ztree> ztrees = new ArrayList<Ztree>();

        SysUser currentUser = ShiroUtils.getSysUser();
        List<String>citys = new ArrayList<>();
        List<String>years = new ArrayList<>();
        boolean isAdmin = true;
        if (currentUser != null&&!currentUser.isAdmin()){
            isAdmin=false;
            String city = currentUser.getCity();
            if(city!=null){
                citys = Arrays.asList(city.split(","));
            }
        }

        for (SysDictData dictData : dictDataList) {
            if(isAdmin || citys.contains(dictData.getDictValue())){
                Ztree ztree = new Ztree();
                ztree.setId(Long.parseLong(dictData.getDictValue()));
                ztree.setName(dictData.getDictLabel());
                ztree.setTitle(dictData.getDictLabel());
                ztrees.add(ztree);
            }
        }
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        for (CreditGrade grade : gradList) {
            //String datef = sdf.format(grade.getCreateTime());
            //创建时间不一定是年度发布时间，比如年度的评分可能在下一年的1月份进行
            String datef="";
            if (grade.getGradePeriod().length()>=4){
                datef=grade.getGradePeriod().toString().substring(0,4);
            }

            if(isAdmin || citys.contains(grade.getCity())) {

                if(!years.contains(grade.getCity()+datef)){
                    Ztree itemTree = new Ztree();
                    itemTree.setId(Long.parseLong(datef));
                    itemTree.setpId(Long.parseLong(grade.getCity()));
                    itemTree.setName(datef);
                    itemTree.setTitle(datef);
                    ztrees.add(itemTree);
                }
            }
            years.add(grade.getCity()+datef);
        }
        return ztrees;

    }

    /**
     * 修改信用评分
     *
     * @param creditGrade 信用评分
     * @return 结果
     */
    @Override
    @Transactional
    public int saveEditGrade(CreditGrade creditGrade) {
        Double totalScore = 0.0;
        Double weight=0.00;
        List<String> scores = creditGrade.getScores();
        List<String> remarks = creditGrade.getRemarks();

        //查询顶层目录评分类型
        List<CreditGradeType> topGradeTypeList=creditGradeTypeMapper.selectTopGradeTypeByGradeId(creditGrade.getId());

        //获取同样排序的评分细则数据
        ItemGradeRelation condition = new ItemGradeRelation();
        condition.setGradeId(creditGrade.getId());
        List<ItemGradeRelation> relationList = itemGradeRelationMapper.selectItemGradeRelationList(condition);

        //评分数据集
        List<ItemGradeRelation> itemGradeRelationList = new ArrayList<>();
        for (int i = 0; i < scores.size() && i<remarks.size(); i++) {

            ItemGradeRelation originalGrade =relationList.get(i);
            ItemGradeRelation updateCondition =new ItemGradeRelation();
            updateCondition.setGradeId(creditGrade.getId());
            updateCondition.setItemId(originalGrade.getItemId());
            updateCondition.setScore(Double.parseDouble(scores.get(i)));
            updateCondition.setRemark(remarks.get(i));

            originalGrade.setScore(Double.parseDouble(scores.get(i)));
            itemGradeRelationList.add(originalGrade);

            itemGradeRelationMapper.updateByGradeIdItemId(updateCondition);
        }

        //按照不同的顶层目录计算分数
        String typeIds="";
        Double totalScore_Deduct = 0.00; //顶层可抵扣分数
        Double totalScore_NoDeduct=0.00; //顶层不可抵扣分数
        for(int j=0;j<topGradeTypeList.size();j++){
            //获取该顶层目录下的分类数据
            totalScore_Deduct=0.00;
            totalScore_NoDeduct=0.00;
            typeIds=creditGradeTypeMapper.selectGradeTypeChilds(topGradeTypeList.get(j));
            String[] arr_TypeIds=Convert.toStrArray(typeIds);
            for(int k=0;k<itemGradeRelationList.size();k++){
                ItemGradeRelation itemGradeRelation=itemGradeRelationList.get(k);
                if (itemGradeRelation!=null && Arrays.asList(arr_TypeIds).contains(itemGradeRelation.getTypeId().toString())){
                    // 计算可抵扣分数
                    if (itemGradeRelation.getDeductFlag().equals("0") && itemGradeRelation.getWeight()==null) {
                        totalScore_Deduct += itemGradeRelation.getScore();
                    }else if (itemGradeRelation.getDeductFlag().equals("0") && itemGradeRelation.getWeight()!=null){
                        totalScore_Deduct += itemGradeRelation.getWeight()*itemGradeRelation.getScore()/100;
                    }

                    //计算不可抵扣分数
                    if (itemGradeRelation.getDeductFlag().equals("1") && itemGradeRelation.getWeight()==null) {
                        totalScore_NoDeduct += itemGradeRelation.getScore();
                    }else if (itemGradeRelation.getDeductFlag().equals("1") && itemGradeRelation.getWeight()!=null){
                        totalScore_NoDeduct += itemGradeRelation.getWeight()*itemGradeRelation.getScore()/100;
                    }
                }
            }
            //判断该顶层目录是否存在封顶分数
            if (topGradeTypeList.get(j).getMaxScore()!=null && topGradeTypeList.get(j).getMaxScore()<totalScore_Deduct){
                totalScore_Deduct=Double.parseDouble(topGradeTypeList.get(j).getMaxScore().toString());
            }

            totalScore+=totalScore_Deduct+totalScore_NoDeduct;
        }

        //更新CreditGrade
        CreditGrade updateCreditGrade = new CreditGrade();
        updateCreditGrade.setId(creditGrade.getId());
        updateCreditGrade.setUpdateTime(DateUtils.getNowDate());
        updateCreditGrade.setTotalScore(totalScore);

        creditGradeMapper.updateCreditGrade(updateCreditGrade);

        return 1;
    }

    /**
     * 修改信用评分
     *
     * @param creditGrade 信用评分
     * @return 结果
     */
    @Override
    public int updateCreditGrade(CreditGrade creditGrade) {
        creditGrade.setUpdateTime(DateUtils.getNowDate());
        return creditGradeMapper.updateCreditGrade(creditGrade);
    }

    /**
     * 批量删除信用评分
     *
     * @param ids 需要删除的信用评分主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCreditGradeByIds(String ids) {
        itemGradeRelationMapper.deleteItemGradeRelationByGradeIds(Convert.toStrArray(ids));
        creditGradeTypeMapper.deleteCreditGradeTypeByGradeIds(Convert.toStrArray(ids));
        return creditGradeMapper.deleteCreditGradeByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除信用评分信息
     *
     * @param id 信用评分主键
     * @return 结果
     */
    @Override
    public int deleteCreditGradeById(Long id) {
        itemGradeRelationMapper.deleteItemGradeRelationByGradeId(id);
        creditGradeTypeMapper.deleteCreditGradeTypeByGradeId(id);
        return creditGradeMapper.deleteCreditGradeById(id);
    }

    /**
     * 修改诊断书
     *
     * @param creditGrade 诊断书
     * @return 结果
     */
    @Override
    @Transactional
    public int saveEditDiagnose(CreditGrade creditGrade) {
        /*List<String> diagnoseRemark = creditGrade.getDiagnoseRemark();

        //获取同样排序的评分细则数据
        ItemGradeRelation condition = new ItemGradeRelation();
        condition.setGradeId(creditGrade.getId());
        List<ItemGradeRelation> relationList = itemGradeRelationMapper.selectItemGradeRelationDiagnoseList(condition);

        for (int i = 0; i < diagnoseRemark.size(); i++) {
            ItemGradeRelation originalGrade =relationList.get(i);
            ItemGradeRelation updateCondition =new ItemGradeRelation();
            updateCondition.setGradeId(creditGrade.getId());
            updateCondition.setItemId(originalGrade.getItemId());
            updateCondition.setDiagnoseRemark(diagnoseRemark.get(i));

            itemGradeRelationMapper.updateByGradeIdItemId(updateCondition);
        }*/

        creditGradeMapper.updateCreditGrade(creditGrade);
        return 1;
    }
}
